package sample.service;

import cn.hutool.core.util.ArrayUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

//带着这个servie注解，授权码模式会报错：No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken
@Service
public class SiteUserDetailsServiceImpl implements SiteUserDetailsService {

    /**
     * 角色前缀
     */
    String ROLE = "ROLE_";

    @Autowired
    private SiteCustomerMapper siteCustomerMapper;

    /**
     * 用户密码登录
     * @param userName
     * @return {org.springframework.security.core.userdetails.UserDetails}
     * @author 管传杰
     * @date 2022/3/17 11:36
    */
    @Override
    public SiteUser loadUserByUsername(String userName) throws UsernameNotFoundException {
        //根据登录名查询用户信息
        SiteCustomerVO customer = new SiteCustomerVO();
        customer.setUserName(userName);
        SiteCustomerVO siteCustomer = siteCustomerMapper.getCustomerInfo(customer);
////        customer.setUserName(userName);
//        customer.setEmail(userName);
//        ResponseMessage<SiteCustomerVO> result = siteCustomerApi.customerInfo(customer);
//
        if (siteCustomer == null) {
            siteCustomer = new SiteCustomerVO();
        }
        // 设置角色列表 （ID）
        List<Integer> roleIds = new ArrayList<Integer>();
        roleIds.add(1);
        siteCustomer.setRoles(ArrayUtil.toArray(roleIds, Integer.class));

        // 设置权限列表（menu.permission）
        Set<String> permissions = new HashSet<>();
        permissions.add("admin");
        siteCustomer.setPermissions(ArrayUtil.toArray(permissions, String.class));

        //组装UserDetails
        SiteUser userDetails = getUserDetails(siteCustomer);
        return userDetails;
    }

    /**
     * 构建userdetails
     * @param siteCustomer 用户信息
     * @return
     */
    private SiteUser getUserDetails(SiteCustomerVO siteCustomer) {

        Set<String> dbAuthsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(siteCustomer.getRoles())) {
            // 获取角色
            Arrays.stream(siteCustomer.getRoles()).forEach(roleId -> dbAuthsSet.add(ROLE + roleId));
            // 获取资源
            dbAuthsSet.addAll(Arrays.asList(siteCustomer.getPermissions()));

        }
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils
                .createAuthorityList(dbAuthsSet.toArray(new String[0]));
        // 构造security用户
//        SiteUser user = new SiteUser(siteCustomer.getUserName(), siteCustomer.getPassword(), authorities);
        SiteUser user = new SiteUser(siteCustomer.getId(), siteCustomer.getUserName(), siteCustomer.getPassword(), authorities);
        return user;
    }

}
